import math
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from StudyPlatform.models import Grade, Courses


# 全部课程首页
@login_required(login_url='login')
def allCourses(request, grade_url, subject, page):
    page = int(page)
    if request.method == "POST":
        if subject == "allCourses":
            courses = Courses.objects.filter(grade__gradeurl=grade_url).all()[(page-1)*9:page*9]
            counts = Courses.objects.filter(grade__gradeurl=grade_url).all().count()
        else:
            courses = Courses.objects.filter(grade__gradeurl=grade_url, courseurl=subject).all()[(page-1)*9:page*9]
            counts = Courses.objects.filter(grade__gradeurl=grade_url, courseurl=subject).all().count()
        numbers = []
        for n in range(1, math.ceil(counts / 9) + 1):
            numbers.append(n)
        context = {
            "courses": courses,
            "counts": counts,
            "numbers": numbers,
            "maxPage": len(numbers),
            "grade_url": grade_url,
            "subject": subject,
            "page": page,
            'pre': page - 1,
            'next': page + 1,
        }
        return render(request, "ajax/ajax_courses_main.html", context)
    else:
        grade = Grade.objects.all()
        courses = Courses.objects.filter(grade__gradeurl=grade_url).values('coursename', 'courseurl').distinct()
        context = {
            "grade": grade,
            "courses": courses,
            "grade_url": grade_url,
            "subject": subject,
            "page": page,
        }
        return render(request, "all_courses.html", context)